package com.hotec.PROJECT_NAME.modules.sys.service;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import com.hotec.PROJECT_NAME.component.basic.SmsConfigure;
import com.hotec.PROJECT_NAME.component.enums.SmsEnum;
import com.hotec.PROJECT_NAME.component.exception.exc.BizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@Service("unionpaySmsService")
public class UnionPaySmsService extends AbstractSmsService {
    @Autowired
    private SmsConfigure smsConfigure;

    @Override
    void postMsg(String mobile, SmsEnum type, String smsCode) {
        SmsConfigure.UnionPay unionPayConfigure = smsConfigure.getUnionpay();

        String url = unionPayConfigure.getUrl();
        String apiKey = unionPayConfigure.getApiKey();
        String username = unionPayConfigure.getUsername();
        String password = unionPayConfigure.getPassword();
        String template = unionPayConfigure.getTemplate();

        Map<String, Object> sendParam = Maps.newLinkedHashMap();
        sendParam.put("format", "json");

        JSONObject jsonData = new JSONObject();
        jsonData.set("type", "send");
        jsonData.set("username", username);
        jsonData.set("password_md5", MD5.create().digestHex(password));
        jsonData.set("apikey", apiKey);
        jsonData.set("encode", StandardCharsets.UTF_8);
        jsonData.set("mobile", mobile);
        jsonData.set("content", StrUtil.format(template, smsCode));

        sendParam.put("data", jsonData.toJSONString(2));

        String responseText = HttpUtil.get(url, sendParam);

        try {
            if(StrUtil.startWith(responseText, "error:")) throw new BizException(responseText);

            Map<String, Object> responseMap = JSONUtil.toBean(responseText, new TypeReference<Map<String, Object>>() {
            }, true);

            String status = MapUtil.getStr(responseMap, "status");

            Assert.isTrue(StrUtil.equalsIgnoreCase(status, "success"), MapUtil.getStr(responseMap, "msg"));
        } catch (Exception e) {
            throw new BizException(StrUtil.format("短信发送异常[{}]", e.getMessage()));
        }
    }
}
